import { useRef, useCallback } from 'react';
import useUpdate from './useUpdate';

export default function useLockFn(fn) {
  const forceUpdate = useUpdate();
  const { current } = useRef({
    fn,
    loading: false,
  });
  current.fn = fn;

  const lockFn = useCallback(params => {
    if (current.loading) return;
    current.loading = true;
    current.fn(params).then(() => {
      current.loading = false;
      forceUpdate();
    });
    forceUpdate();
  }, []);

  return [current.loading, lockFn];
}
